package com.muki.spider.core;

import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;


/**
 * uri队列管理池
 * @author ljh_2017
 *
 */

public class UriQueueManagerPool {

	private final Logger log = Logger.getLogger(UriQueueManagerPool.class);
	private final ConcurrentMap<String,BlockingQueue<String>> pool = new ConcurrentHashMap<>();
	private static final UriQueueManagerPool manager = new UriQueueManagerPool();

	public static UriQueueManagerPool getInstance() {
		return manager;
	}

	public void putUrl(String topic,String uri) {
		/**
		 * 根据入口获取队列
		 * 若是新入口，则创建队列
		 */
		BlockingQueue<String> queue = pool.getOrDefault(topic, new LinkedBlockingQueue<String>());
		try {
			//将uri推送入队列中
			queue.put(uri);
			pool.put(topic, queue);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public String getUrl(String topic) throws InterruptedException {
		/**
		 * 根据队列入口得到队列
		 * 若未能从map中查找到对应入口
		 * 则返回空
		 */
		BlockingQueue<String> queue = pool.getOrDefault(topic, null);
		if(queue==null)
			return null;
		return queue.poll(2, TimeUnit.MINUTES);
	}

	public Set<String> getUrlTopics() {
		return pool.keySet();
	}

	public int getUrlCount(String topic) {
		BlockingQueue<String> queue = pool.getOrDefault(topic, null);
		if(queue==null)
			return 0;
		return queue.size();
	}
}
